package com.aduerr.v1shouyin.mvp.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.BindGuidModel;
import com.aduerr.v1shouyin.util.CommonData;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.SecrectAction;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.BandOrUnbandGuidResultDialog;
import com.orhanobut.hawk.Hawk;
import okhttp3.*;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

public class BangGuidActivity extends Activity {

    @BindView(R.id.et_acount)
    EditText et_guid;
    @BindView(R.id.et_sebaihao)
    TextView etSebaihao;
    @BindView(R.id.iv_next)
    TextView ivNext;

    private BandOrUnbandGuidResultDialog bandOrUnbandGuidResultDialog;
    private SweetAlertDialog pDialog;
    private BandOrUnbandGuidResultDialog bandGuidfaid;

    /**
     * 网络观察者
     */
//    protected NetChangeObserver mNetChangeObserver = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bang_guid);
        ButterKnife.bind(this);
        initUI();

        /*mNetChangeObserver = new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType type) {
                ToastUtils.showToast(BangGuidActivity.this, type.name());
            }

            @Override
            public void onNetDisConnect() {
                ToastUtils.showToast(BangGuidActivity.this, "网络开小差了");
            }
        };*/

        //开启广播去监听 网络 改变事件
//        NetStateReceiver.registerObserver(mNetChangeObserver);
    }


    public void initUI() {
        if(Hawk.get("DeviceID") != null) {
            etSebaihao.setText(Hawk.get("DeviceID"));
        } else {
            etSebaihao.setText(CommonData.shebeiId());
        }
    }


    //成功了
    // startActivity(new Intent(BangGuidActivity.this, LoginActivity.class));
    @OnClick({R.id.iv_next, R.id.bt_scan_bind})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.iv_next:
                String guid = et_guid.getText().toString().trim();
                if(TextUtils.isEmpty(guid)) {
                    ToastUtils.showToast(BangGuidActivity.this, "输入不能为空");
                    return;
                }
                pDialog = new SweetAlertDialog(BangGuidActivity.this,
                        SweetAlertDialog.PROGRESS_TYPE);
                pDialog.getProgressHelper().setBarColor(Color.parseColor("#005fee"));
                pDialog.setTitleText("正在加载");
                pDialog.setCancelable(true);
                pDialog.show();
                new Thread() {
                    public void run() {
                        postNetForBandGuid(guid);
                    }
                }.start();
                break;
            case R.id.bt_scan_bind:
                Intent intent = new Intent(this, ScanningActivity.class);
                intent.putExtra(Constants.QRCODE_CAPUTER, Constants.BIND_GUID_QR);
                startActivity(intent);
                break;
        }


    }

    //1.绑定Guid   apiblbl.aduer.com   "139QXEKV9Hj"
    private void postNetForBandGuid(String guid1) {
        String deviceID = Hawk.get("DeviceID");
        String url = Constants.BASE_URL+"/api/PosDeviceRegedit";
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = null;
        if(deviceID != null) {
            body = new FormBody.Builder()
                    .add("pos", CommonData.shebeiId())
                    .add("guid", guid1)
                    .add("deviceid", deviceID)
                    .build();
        } else {
            body = new FormBody.Builder()
                    .add("pos", CommonData.shebeiId())
                    .add("guid", guid1)
                    .build();
        }

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String stringjson = response.body().string();
            // "1|10014186|6359444303226545|测试45|许家琪|||"
            getFromString(stringjson);
        } catch(Exception e) {
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(e instanceof SocketTimeoutException) {
                        Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                    } else if(e instanceof ConnectException) {
                        Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }

    }

    //2.解析请求数据
    public void getFromString(String json) {
        BindGuidModel m;
        String s1 = json.substring(1, json.length() - 1);// 去掉返回字符串两边的 "
        String[] str = s1.split("\\|");
        if("1".equals(str[0])) {
//            business_login_submit.setClickable(false);
            String[] ar = new String[7];
            m = new BindGuidModel(str[0], str[1], str[2], str[3], str[4],
                    str.length > 5 ? str[5] : "", str.length > 6 ? str[6] : "");
            m.toString();
            //存入数据库(Hawk数据库中)
            LogUtils.e("绑定结果", m.toString());
            Hawk.put("DeviceID", m.getDeviceId());
            Hawk.put("DeviceSecret", m.getDeviceSecret());

            //存入数据库中
            SecrectAction secrectInstance = new SecrectAction(BangGuidActivity.this);
            String queryData = secrectInstance.queryData();
            if(queryData != null) {
                // 解绑之后再次绑定，清空数据库
                secrectInstance.deleteData();
            }
            ContentValues values = new ContentValues();
            values.put("DeviceID", m.getDeviceId());
            values.put("DeviceSecret", m.getDeviceSecret());
            Long saveData = secrectInstance.saveData(values);
            if(saveData > 0)
                secrectInstance.closeDB();
            // 关闭数据库

//            Logger.d("m"+m);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(pDialog != null) {
                        pDialog.dismiss();//进度条消失
                    }
                    bandOrUnbandGuidResultDialog =
                            new BandOrUnbandGuidResultDialog(BangGuidActivity.this,
                                    R.style.loading_dialog, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bandOrUnbandGuidResultDialog.dismiss();
                        }
                    }, 100);
                    bandOrUnbandGuidResultDialog.show();
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            Intent intent = new Intent(BangGuidActivity.this,
                                    LoginActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }, 3200);

                }
            });
            //隐藏dailog
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(pDialog != null) {
                        pDialog.dismiss();//进度条消失
                    }
                    //失败结果的弹窗
                    bandGuidfaid =
                            new BandOrUnbandGuidResultDialog(BangGuidActivity.this,
                                    R.style.loading_dialog, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bandGuidfaid.dismiss();
                        }
                    }, 101);
                    bandGuidfaid.show();
                }
            });
            return;
        }
    }


}
